package com.ellecity06.debugtools.ui.fragment.request

import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.recyclerview.widget.LinearLayoutManager
import com.ellecity06.debugtools.base.BaseDebugFragment
import com.ellecity06.debugtools.databinding.FragmentDebugRequestListBinding
import com.ellecity06.debugtools.db.DebugToolsDatabase
import com.ellecity06.debugtools.db.dao.RequestDao
import com.ellecity06.debugtools.db.entity.RequestEntity
import com.ellecity06.debugtools.adapter.DebugLoadStateAdapter
import com.ellecity06.debugtools.ui.request_details.DebugRequestDetailActivity
import com.ellecity06.debugtools.widgets.dialog.showAlert
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2023/4/19 17:18
 * @des
 */
internal class DebugRequestListFragment :
    BaseDebugFragment<FragmentDebugRequestListBinding, DebugRequestListViewModel>() {
    private val dao: RequestDao by lazy {
        DebugToolsDatabase.getDatabase(requireActivity()).getRequestDao()
    }
    private val adapter: DebugRequestListAdapter by lazy { DebugRequestListAdapter(::itemClick) }

    private fun itemClick(i: Int, requestEntity: RequestEntity) {
        DebugRequestDetailActivity.launch(this, requestEntity.id ?: 0)
    }

    override fun lazyInit() {
        binding.rv.layoutManager = LinearLayoutManager(requireActivity())
        val debugRequestLoadStateAdapter = DebugLoadStateAdapter(::retry)
        binding.rv.adapter = adapter.withLoadStateFooter(debugRequestLoadStateAdapter)
        adapter.addLoadStateListener {
            if (it.source.refresh is LoadState.NotLoading && it.append.endOfPaginationReached && adapter.itemCount < 1) {
                binding.rv.isVisible = false
                binding.ivEmpty.isVisible = true
            } else {
                binding.rv.isVisible = true
                binding.ivEmpty.isVisible = false
                debugRequestLoadStateAdapter.loadState = LoadState.NotLoading(false)
            }

        }
        lifecycleScope.launch {
            viewModel.data.collectLatest {
                adapter.submitData(it)
            }
//            adapter.loadStateFlow.collect {
//                if (it.append is LoadState.NotLoading && it.append.endOfPaginationReached) {
//                    binding.ivEmpty.isVisible = adapter.itemCount < 1
//                    binding.rv.isVisible = adapter.itemCount>1
//                }
//            }
        }
    }

    override fun initView() {
        baseBinding.ivRight.setOnClickListener {
            requireActivity().showAlert("确定要永久删除全部数据吗") {
                lifecycleScope.launch {
                    dao.deleteAll()
                   adapter.submitData(PagingData.empty())
                }
            }
        }
    }

    private fun retry() {
        adapter.retry()
    }

    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentDebugRequestListBinding {
        return FragmentDebugRequestListBinding.inflate(inflater, container, false)
    }

    override fun initViewModel(): DebugRequestListViewModel {
        return ViewModelProvider(
            this,
            factory = DebugRequestViewModelFactory(dao)
        )[DebugRequestListViewModel::class.java]
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == 101) {
            adapter.refresh()
        }
    }
}